<?php
	function smarty_function_xsearch($params, &$smarty){
		global $data, $_GET, $setupdata, $mysqlclass;
		
		if ($setupdata["modules"]["shop"]["is"]=="1") {
			$shop_tree1 = array();
			$shop_tree2 = array();
			$shop = array();
			$_query = explode(" ",trim(htmlspecialchars(urldecode($_GET["query"]))));
			
			$sql = "SELECT A.*,B.parent AS PAGEID FROM `".$setupdata["table_prefix"]."product_groups` AS A JOIN `".$setupdata["table_prefix"]."data` AS B ON B.value=A.id WHERE B.type='shop_container' AND B.name='shop_products_group_id'";
			$res = $mysqlclass->mysql_my_query($sql,__LINE__, __FILE__);
			while($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
				$shop_tree1[$row["id"]] = $row;
			}
			
			if(count($shop_tree1)>0) {
				$sql = "SELECT * FROM `".$setupdata["table_prefix"]."product_catalog` WHERE ";
				foreach ($shop_tree1 as $item) {
					$sql .= "`parent`='".$item["id"]."' OR";
				}
				$sql = substr($sql,0,-3);
				$res = $mysqlclass->mysql_my_query($sql,__LINE__, __FILE__);
				while($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
					$shop_tree2[$row["id"]] = $row;
				}
			}
			
			
			if(count($shop_tree2)>0) {
				$sql = "SELECT * FROM `".$setupdata["table_prefix"]."product_data` WHERE ";
				foreach ($shop_tree2 as $item) {
					$sql .= "`parent`='".$item["id"]."' OR";
				}
				$sql = substr($sql,0,-3);
				$shop_data = array();
				$res = $mysqlclass->mysql_my_query($sql,__LINE__, __FILE__);
				while($row = mysql_fetch_array($res, MYSQL_ASSOC)) {
					$shop_data[$row["parent"]]["product"][$row["name"]] = $row["value"];
				}
			}
			
			foreach ($shop_data as $key=>$value) {
				if($value["product"]) {
					if(if_found($value["product"], $_query)==true) {
						$value["url"] = $setupdata["base_href"]."/index.php?id=".$shop_tree1[$shop_tree2[$key]["parent"]]["PAGEID"]."&amp;pid=".$key;
						$value["type"] = "product01";
						$value["name"] = $shop_tree2[$key]["name"];
						$shop[] = $value;
					}
				}
			}
			
			$_results = count($shop)>0?$shop + $data["search"]:$data["search"];
			
			if (isset($params["assign"])) $smarty->assign($params["assign"], $_results);
			else return $_results;
		}
	}
  
	function if_found($arr, $_query) {
		$str = "";
		$re = false;
			foreach ($arr as $value) $str .= " ".$value;
			if (strlen($str) > 0){
				foreach ($_query as $q) {
					if($re===false) {
						if (strlen($q) > 0){
							$pos = strpos(strtolower($str),strtolower($q));
						} else $pos = 0;
						if(!is_bool($pos)&&$pos>0) $re = true;
					}
				}
			}
		return $re;
	}
?>
